<template>
  <view class="container">

    
	<view class="form-item">
		<label class="label">电站编号：</label>
		<input 
		  type="text" 
		  v-model="searchQuery" 
		  placeholder="搜索电站 (stationno 或 guestname)" 
		  @input="filterStations"
		  class="search-input"
		/>
		
		<view v-if="filteredStations.length" class="dropdown">
		  <view 
			v-for="station in filteredStations" 
			:key="station.id" 
			@click="selectStation(station.id)">
			{{ station.displayName }}
		  </view>
		</view>
	</view>
	
    <view class="form-item">
      <label class="label">客户姓名：</label>
      <view class="input">{{ selectedStation.guestname }}</view>
    </view>

    <view class="form-item">
      <label class="label">联系电话：</label>
      <view class="input">{{ selectedStation.phone }}</view>
    </view>

    <view class="form-item">
      <label class="label">地址：</label>
      <view class="input">{{ selectedStation.addressstring }}</view>
    </view>
    
	<view class="form-item">
      <label class="label" for="description">故障描述：</label>
      <textarea id="description" class="textarea" v-model="description" placeholder="请输入故障描述"></textarea>
    </view>
	
	<view class="form-item">
		<view class="upload-header">
			<text class="label">图片上传：</text>
		</view>
		<view class="upload-grid">
			<view v-for="(img, index) in previewImage" :key="index" class="image-wrapper">
			  <image :src="img" class="uploaded-image" mode="aspectFill" />
			  <view class="delete-icon" @click="removeImage(index)">✖</view>
			</view>
			<view class="upload-add" @click="tupian">
			  <image src="/static/camera-icon.png" class="camera-icon" mode="aspectFit" />
			</view>
		</view>
	</view>
	
    
    <button @click="submitFault">提交</button>
  </view>
</template>

<script>
import request from '@/utils/request.js';
import { getAccessToken } from '@/utils/auth';	
	
export default {
  data() {
    return {
		searchQuery: '',
		stations: [],
		filteredStations: [],
		token: getAccessToken(),
		selectedStation: {
		  id: null,
		  stationno: '',
		  guestname: '',
		  phone: '',
		  addressstring: '',
		  provinceId: null,
		  cityId: null,
		  areaId: null,
		},
		displayName: '',
		description: '',
		previewImage:[],
		locationPicUrls:[],
		
    };
  },
  async created() {
    await this.fetchStations();
  },
  methods: {
    async fetchStations() {
          try {
            console.log("开始请求电站列表...");
            const res = await request({
              url: "/oper/station/page?pageSize=100",
              method: 'GET',
              headers: { Authorization: `Bearer ${this.token}` }
            });
            console.log("API 返回数据:", res);
            
    		this.stations = res.data.list.map(station => ({
    			id: station.id,
    			stationno: station.stationno,
    			guestname: station.guestname,
    			displayName: `${station.stationno} - ${station.guestname}`,
    			phone: station.phone,
    			addressstring: station.addressstring
    		}));
    		console.log("解析后的电站数据:", this.stations);
          } catch (error) {
            console.error("获取电站列表失败", error);
          }
        },

	//图片
	tupian(){
		uni.chooseImage({
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				console.log("缩略图",this.previewImage);
				uni.uploadFile({
					url: 'http://123.60.139.112:48080/admin-api/infra/file/upload', 
					header: { Authorization: `Bearer ${this.token}` },
					filePath: tempFilePaths[0],
					name: 'file',
					formData: {
						'user': 'test'
					},
					success: (res) => {
						console.log('Success:', res.statusCode, res.data);
						try {
							const responseData = JSON.parse(res.data);
							if (responseData.code === 0) {
							  this.locationPicUrls.push(responseData.data);
							  this.previewImage = this.locationPicUrls;
							} else {
							  console.error('上传失败:', responseData.msg);
							}
						} catch (error) {
							console.error('解析响应失败:', error);
						}
					},
					fail: (err) => {
						console.error('Fail:', err.errMsg);
					},
					complete: (res) => {
						console.log('Complete:', res);
					}
					
				});
			}
		});		
	},
	
	
	
	
    filterStations() {
      const query = this.searchQuery.toLowerCase();
      this.filteredStations = this.stations.filter(station => 
        station.stationno.toLowerCase().includes(query) ||
        station.guestname.toLowerCase().includes(query)
      );
    },
	async selectStation(stationId) {
	  try {
		const res = await request({
		  url: `/oper/station/get?id=${stationId}`,
		  method: 'GET',
		  headers: { Authorization: `Bearer ${this.token}` }
		});
		console.log("获取电站详情返回:", res);
		
		if (res.data) {
		  this.selectedStation = {
			...this.selectedStation,
			id:  res.data.id,
			stationno:  res.data.stationno,
			guestname: res.data.guestname,
			displayName: `${ res.data.stationno} - ${ res.data.guestname}`,
			phone:  res.data.phone,
			addressstring:  res.data.addressstring,
			provinceId: res.data.provinceId,
			cityId: res.data.cityId,
			areaId: res.data.areaId
		  };
		}
		console.log("选中站:", this.selectedStation);
		this.searchQuery = this.selectedStation.displayName;
		this.filteredStations = [];
	  } catch (error) {
		console.error("获取电站详情失败", error);
	  }
	},

    async submitFault() {
	  console.log("xuanzhong:", this.selectedStation);
	  
      const data = {
        id: 0,
        stationId: this.selectedStation.id,
        stationno: this.selectedStation.stationno,
        guestname: this.selectedStation.guestname,
        phone: this.selectedStation.phone,
        addressstring: this.selectedStation.addressstring,
        provinceId: this.selectedStation.provinceId,
        cityId: this.selectedStation.cityId,
        areaId: this.selectedStation.areaId,
        status: 1,
        description: this.description,
        picUrls: this.locationPicUrls[0],
        node: 0
      };
      
      console.log("提交故障单数据:", data);
      const res = await request({
        url: '/oper/fault/create',
        method: 'POST',
        data: data,
        headers: { Authorization: `Bearer ${this.token}` }
      });
      
      if (res.code === 0) {
        uni.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 2000,
          success: () => {
            setTimeout(() => {
              uni.navigateBack();
            }, 2000);
          }
        });
      } else {
        uni.showToast({
          title: '提交失败',
          icon: 'none'
        });
      }
    }
	
	
	
  }
};
</script>

<style lang = "scss">
.container {
  padding: 24rpx;
  background-color: white;
  
}

.form-item {
  margin: 32rpx;
  justify-content: center;
}

.label {
  display: block;
  font-size: 28rpx;
  margin-bottom: 16rpx;
  font-weight: bolder;
}

.input {
  height: 80rpx;
  padding: 9px;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  font-size: 15px;
}

.textarea{
	width: 100%;
	padding: 0 20rpx;
	border: 1rpx solid #eee;
	border-radius: 8rpx;
	font-size: 15px;
}

.submit-btn {
  margin-top: 48rpx;
  background: #007AFF;
  color: white;
}



.dropdown {
  position: absolute;
  width: 100%;
  background-color: #fff;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
  z-index: 10;
  max-height: 300rpx; // 设置最大高度
  overflow-y: auto;   // 启用垂直滚动条
  font-size: 20px;

  // 自定义滚动条 (Webkit 浏览器)
  &::-webkit-scrollbar {
    width: 8rpx;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #ccc;
    border-radius: 4rpx;
  }

  &::-webkit-scrollbar-track {
    background-color: #f9f9f9;
  }

  > view {
    padding: 12rpx 16rpx;
    cursor: pointer;
    font-size: 28rpx;
    transition: background-color 0.2s ease;

    &:hover {
      background-color: #f5f5f5;
    }
  }
}

</style>

<style lang="scss" scoped>
.upload-header {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
}

.upload-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  margin-top: 10rpx;
  margin-bottom: 50rpx;
  

  .image-wrapper {
    position: relative;
    width: 100%;
    aspect-ratio: 1 / 1;

    .uploaded-image {
      width: 100%;
      height: 100%;
      border-radius: 5rpx;
      object-fit: cover;
      border: 1rpx solid #ddd;
    }

    .delete-icon {
      position: absolute;
      top: 5rpx;
      right: 5rpx;
      width: 36rpx;
      height: 36rpx;
      background-color: rgba(0, 0, 0, 0.6);
      color: #fff;
      text-align: center;
      line-height: 36rpx;
      border-radius: 50%;
      cursor: pointer;
      font-size: 24rpx;
    }
  }

  .upload-add {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    aspect-ratio: 1 / 1;
    border: 2rpx dashed #aaa;
    border-radius: 5rpx;
    cursor: pointer;

    .camera-icon {
      width: 80rpx;
      height: 80rpx;
    }
  }
}

</style>
